import { message } from 'antd'
import axios from 'axios'
import { getToken, removeToken } from './storage'
import history from './history'
export const baseURL = 'http://geek.itheima.net/v1_0/'
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000,
})
// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return error
  }
)
// 响应拦截器
instance.interceptors.response.use(
  function (res) {
    return res.data
  },
  function (error) {
    console.log(error.response)
    if (!error.response) {
      message.error('网络繁忙，请稍后重试')
      return Promise.reject(new Error('网络繁忙，请稍后重试'))
    }
    if (error.response.status === 401) {
      // token过期
      removeToken()
      message.warn('登录信息过期了')
      // window.location.href = '/login'
      history.push('/login')
    }
    return Promise.reject(error)
  }
)
export default instance
